<?php

namespace addons\xilumarket\chatprograms\library;

use app\common\library\Token;
use app\common\model\User;

class UserAuth
{
    /**
     * 根据Token初始化
     *
     * @param string $token Token 84fec134257974bdcccbf70050e43fa2
     * @return array
     */
    public function init($token)
    {
        $data = Token::get($token);
        if (!$data) {
            return ['status' => false, 'msg' => '账号不存在'];
        }
        $user_id = intval($data['user_id']);
        if ($user_id > 0) {
            $user = User::get($user_id);
            if (!$user) {
                return ['status' => false, 'msg' => '账号不存在'];
            }
            if ($user['status'] != 'normal') {
                return ['status' => false, 'msg' => '账号已被拉黑'];
            }
            //判断连续登录和最大连续登录
            if ($user->logintime < \fast\Date::unixtime('day')) {
                $user->successions = $user->logintime < \fast\Date::unixtime('day', -1) ? 1 : $user->successions + 1;
                $user->maxsuccessions = max($user->successions, $user->maxsuccessions);
            }
            $user->prevtime = $user->logintime;
            $user->loginip = request()->ip();
            $user->logintime = time();
            //重置登录失败次数
            $user->loginfailure = 0;
            $user->save();
            return ['status' => true, 'data' => $user];
        } else {
            return ['status' => false, 'msg' => '账号不存在'];
        }
    }
}
